﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using MessageBox = System.Windows.Forms.MessageBox;
using Path = System.IO.Path;

namespace DocxHelper
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private CancellationTokenSource _cancellationTokenSource;

        public MainWindow()
        {
            InitializeComponent();
            var writer = new TextBoxWriter(this.TbConsole);
            Console.SetOut(writer);
            Console.WriteLine("程序已就绪");
            Console.WriteLine("若剪裁为0，则不对源图片进行剪裁");
            Console.WriteLine("若页面宽度为0，则不对转出的图片进行缩放");
        }

        private void TbSourceDir_OnMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            using (var dialog = new FolderBrowserDialog())
            {
                var result = dialog.ShowDialog();
                if (result == System.Windows.Forms.DialogResult.OK)
                {
                    this.TbSourceDir.Text = dialog.SelectedPath;
                }
            }
        }

        private void TbWater_OnMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            using (var dialog = new OpenFileDialog())
            {
                dialog.CheckFileExists = true;
                dialog.DefaultExt = ".png";
                dialog.Multiselect = false;
                var result = dialog.ShowDialog();
                if (result == System.Windows.Forms.DialogResult.OK)
                {
                    this.TbWater.Text = dialog.FileName;
                }
            }
        }

        private async void BtnStart_OnClick(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(this.TbSourceDir.Text))
            {
                Console.WriteLine("错误：请选择源文件夹");
                return;
            }
            if (!Directory.Exists(this.TbSourceDir.Text))
            {
                Console.WriteLine("错误：源文件夹不存在");
                return;
            }

            if (!int.TryParse(this.TbWidth.Text, out var maxWidth) || maxWidth < 0)
            {
                Console.WriteLine("错误：页面宽度必须是非负整数");
                return;
            }

            if (!int.TryParse(this.TbPages.Text, out var pages) || pages < 1)
            {
                Console.WriteLine("错误：提取页数必须是正整数");
                return;
            }

            if (!int.TryParse(this.TbCut.Text, out var cut))
            {
                Console.WriteLine("错误：剪裁量必须是非负整数");
                return;
            }

            var query = Directory.EnumerateFiles(this.TbSourceDir.Text, "*.docx", SearchOption.AllDirectories)
                .Where(f => !Path.GetFileName(f).StartsWith("~"));

            if (this.ChbSkipExist.IsChecked == true)
            {
                query = query.Where(f =>
                {
                    var png = Path.Combine(Path.GetDirectoryName(f), Path.GetFileNameWithoutExtension(f) + "-1.png");
                    return !File.Exists(png);
                });
            }
            var files = query.ToList();
            if (files.Count == 0)
            {
                Console.WriteLine("没有待转换的文件");
                return;
            }
            if (MessageBox.Show($"需要转换{files.Count}个文件，是否继续？", "确认", MessageBoxButtons.YesNo)
                != System.Windows.Forms.DialogResult.Yes)
            {
                return;
            }

            this.BtnStart.IsEnabled = false;
            this.BtnCancel.IsEnabled = true;

            _cancellationTokenSource = new CancellationTokenSource();
            var water = this.TbWater.Text;
            await Task.Run(() =>
             {
                 try
                 {
                     using (var converter = new DocxConverter(water))
                     {
                         for (var i = 0; i < files.Count; i++)
                         {
                             if (_cancellationTokenSource.IsCancellationRequested)
                             {
                                 Console.WriteLine("任务已取消");
                                 break;
                             }

                             Console.WriteLine($"{i + 1}/{files.Count} 开始转换 {files[i]}");
                             converter.ToImage(files[i], maxWidth, pages, cut);
                         }
                     }
                 }
                 catch (Exception ex)
                 {
                     Console.WriteLine("错误：" + ex.Message);
                 }
             });
            Console.WriteLine("任务完成");
            this.BtnStart.IsEnabled = true;
            this.BtnCancel.IsEnabled = false;
        }

        private void BtnCancel_OnClick(object sender, RoutedEventArgs e)
        {
            _cancellationTokenSource?.Cancel();
        }

        private void TbConsole_OnMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            this.TbConsole.Clear();
        }
    }
}
